import React, { useState, useRef, useEffect } from 'react';
import { Sun, Moon, Monitor, Check } from 'lucide-react';
import { useTheme } from '../contexts/ThemeContext';

interface ThemeOption {
  value: 'light' | 'dark' | 'system';
  label: string;
  icon: React.ReactNode;
  description: string;
}

const themeOptions: ThemeOption[] = [
  {
    value: 'light',
    label: 'Light',
    icon: <Sun size={18} />,
    description: '浅色模式',
  },
  {
    value: 'dark',
    label: 'Dark',
    icon: <Moon size={18} />,
    description: '深色模式',
  },
  {
    value: 'system',
    label: 'System',
    icon: <Monitor size={18} />,
    description: '跟随系统',
  },
];

const ThemeSwitcher: React.FC = () => {
  const { theme, setTheme } = useTheme();
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const currentThemeOption = themeOptions.find(option => option.value === theme) || themeOptions[2];

  const handleThemeChange = (newTheme: 'light' | 'dark' | 'system') => {
    setTheme(newTheme);
    setIsOpen(false);
  };

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 px-3 py-2 rounded-lg bg-white/10 dark:bg-white/5 hover:bg-white/20 dark:hover:bg-white/10 transition-all duration-200 text-white border border-white/20 dark:border-white/10 hover:border-white/30 backdrop-blur-sm group"
        aria-label="Change theme"
        title={`Current: ${currentThemeOption.label}`}
      >
        <div className="text-[#00d4ff] transition-transform duration-200 group-hover:rotate-12">
          {currentThemeOption.icon}
        </div>
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-3 w-48 bg-white dark:bg-gray-800 backdrop-blur-xl rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 py-1 z-50 overflow-hidden opacity-0 scale-95 animate-[fadeIn_200ms_ease-out_forwards]">
          <div className="px-3 py-2 text-xs font-bold text-gray-500 dark:text-gray-400 uppercase tracking-wider border-b border-gray-100 dark:border-gray-700">
            Theme
          </div>
          {themeOptions.map((option) => (
            <button
              key={option.value}
              onClick={() => handleThemeChange(option.value)}
              className={`w-full px-4 py-3 text-left transition-all duration-200 flex items-center justify-between group ${
                theme === option.value
                  ? 'bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400'
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              }`}
            >
              <div className="flex items-center gap-3">
                <div className={`${theme === option.value ? 'text-blue-600 dark:text-blue-400' : 'text-gray-500 dark:text-gray-400'}`}>
                  {option.icon}
                </div>
                <div className="flex flex-col">
                  <span className={`font-semibold text-sm ${theme === option.value ? 'text-blue-600 dark:text-blue-400' : 'text-gray-900 dark:text-gray-100'}`}>
                    {option.label}
                  </span>
                  <span className={`text-xs ${theme === option.value ? 'text-blue-500/70 dark:text-blue-400/70' : 'text-gray-500 dark:text-gray-400'}`}>
                    {option.description}
                  </span>
                </div>
              </div>
              {theme === option.value && (
                <Check size={18} className="text-blue-600 dark:text-blue-400" strokeWidth={3} />
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

export default ThemeSwitcher;
